# -*- coding: utf-8 -*-#
#-------------------------------------------------------------------------------
# 建立者:        博智科技  
# Name:         camera_thread
# Description:
# Author:       yzl
# Date:         2019-04-21
#-------------------------------------------------------------------------------

import cv2
from threading import Thread

# 多线程，高效读视频

class WebcamVideoStream:
    def __init__(self, src, width, height):
        # 初始化摄像头,都取一帧
        self.stream = cv2.VideoCapture(src)
        self.stream.set(cv2.CAP_PROP_FRAME_WIDTH, width)
        self.stream.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
        (self.grabbed, self.frame) = self.stream.read()

        # 初始化停止线程标识
        self.stopped = False

    def start(self):
        # 开启线程,从视频流中读帧
        Thread(target=self.update, args=()).start()
        return self

    def update(self):
        # 持续读,直到停止
        while True:
            # if the thread indicator variable is set, stop the thread
            if self.stopped:
                return

            # 读帧
            (self.grabbed, self.frame) = self.stream.read()

    def read(self):
        # 返回帧
        return self.frame

    def stop(self):
        # 线程停止
        self.stopped = True

# 使用方法
# video_capture = WebcamVideoStream(src=video_source,
#                                       width=width,
#                                       height=height).start()
# frame = video_capture.read()

